package com.heima.xxlJob.job;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class XxlJobQuickstart {

    @Value("${xxl.job.executor.port}")
    private String port;

    //需求：给系统所有用户发放优惠券，考虑用户量庞大，要求使用分片广播模式
    @XxlJob("demoJobHandler")
    public void helloJob(){
        log.info("定时任务执行了。。。。");
        //1.先分片：1.当前片索引；2.总分片数量
        int shardIndex = XxlJobHelper.getShardIndex();//1
        int shardTotal = XxlJobHelper.getShardTotal();//2

        //2.遍历任务集合，拿到每任务的序号
        List<Integer> users = getUsers();
        for (int i = 0;i < users.size();i++){
            //3.分片计算：拿当前任务序号%分片总数=当前分片索引
            if (i%shardTotal == shardIndex){
                System.out.println(port+"给用户" + users.get(i)+"发放优惠劵"+shardIndex);
            }
        }

    }

    private List<Integer> getUsers(){
        List<Integer> users = new ArrayList<>();
        for (int id = 1;id <= 10;id++){
            users.add(id);
        }
            return users;
    }
}